package com.example.controller;

import com.example.utils.PersonalTool;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.web.socket.CloseStatus;

/**
 * 业务处理类 必须继承 TextWebSocketHandler
 * 这里是继承文本类消息处理实例类
 * ws消息包含文本类和二进制类
 */
public class MyWebSocketHandler extends TextWebSocketHandler {

    // 使用线程安全的ConcurrentHashMap存储所有在线客户端
    private static final Map<String, WebSocketSession> clients = new ConcurrentHashMap<>();

    /**
     * 客户端连接建立后执行
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 将新连接的客户端添加到集合中
        // 使用session.getId()作为客户端唯一标识
        clients.put(session.getId(), session);
        System.out.println("New client connected: " + session.getId());
    }

    /**
     * 客户端连接关闭后执行
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 从集合中移除断开连接的客户端
        clients.remove(session.getId());
        System.out.println("Client disconnected: " + session.getId());
    }

    /**
     * 处理消息逻辑
     * @param session 客户端身份信息
     * @param message 消息体
     * @throws IOException 输入输出异常
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
        // todo 这里可以处理用户分组，消息转发，广播等功能
        // 获取消息内容
        String payload = message.getPayload();
        // 处理接收到的消息
        System.out.println("Received message: " + payload);
        //String sql = "SELECT * FROM users order by id desc";
        //Map<String, Object> params = new HashMap<>();
        //Map<String, Object> result = PersonalTool.queryDataFromMysql(sql, params);

        Map<String,Object> result = new HashMap<>();
        result.put("message", "success");
        result.put("status", 200);
        result.put("data", new ArrayList<>());
        // 向所有已连接的客户端转发消息
        broadcastMessage(PersonalTool.response(result, 200, payload));
    }

    /**
     * 向所有客户端群发消息
     * @param message 要发送的消息内容
     */
    private void broadcastMessage(String message) {
        TextMessage textMessage = new TextMessage(message);

        // 遍历所有客户端并发送消息
        for (WebSocketSession client : clients.values()) {
            try {
                // 检查客户端连接状态
                if (client.isOpen()) {
                    client.sendMessage(textMessage);
                }
            } catch (IOException e) {
                // 处理发送失败的情况
                System.err.println("Error sending message to client: " + e.getMessage());
                // e.printStackTrace();
            }
        }
    }
}